import { Component, OnInit } from '@angular/core';
import {PageSubject} from "../../../../util/page-subject";
import {SourceService} from "./source.service";
import {ResponseUtil} from "../../../../util/response-util";
import {OneDialogService} from "../../../../widgets/one-dialog/one-dialog.service";
import {Path} from "../../../../portal/admin/admin-breadcrumb/breadcrumb";
import {MsgConstants} from "../../../../constants/constants";
import {MsgResult} from "../../../../models/msg-result";
import {PieCharts} from "./pieCharts";
declare var $;
declare var echarts;
declare var moment;

@Component({
  selector: 'app-source',
  templateUrl: './source.component.html',
  styleUrls: ['./source.component.css']
})
export class SourceComponent implements OnInit {
  config;
  config2;
  echartDataObj;
  pieCharts= new PieCharts();
  constructor(
    private pageSubject : PageSubject,
    private sourceService : SourceService,
    private responseUtil :ResponseUtil,
    private dialogService: OneDialogService,
  ) { }

  ngOnInit() {
    this.pushPage();
    this.initTime();
   // this.initButtonEvent();
    this.search();
    this.getTraceSourceData({"startTime":$("#startTime").val(),"endTime":$("#endTime").val()});
  }


//面包屑导航
  pushPage() {
    let path = new Path("溯源追踪", "");
    this.pageSubject.pushPage("溯源追踪曲线", "", path);
  }

  //初始化日期插件
  initTime(){
    let timeData = moment().format("YYYY-MM-DD HH:mm:ss");
    let startDate = moment().subtract(7, "days").format("YYYY-MM-DD HH:mm:ss");

    this.config = {
      timePicker:true,
      timePickerIncrement:1,
      singleDatePicker: true,
      timePicker24Hour:true,
      parentEl:$(".wrapper"),
      maxDate:moment().format("YYYY-MM-DD HH:mm:ss"),
      locale:{
        format:"YYYY-MM-DD HH:00:00",
        separator: " 至 ",
        applyLabel : '确定',
        cancelLabel : '取消',
        fromLabel: '从',
        toLabel: '到',
        weekLabel: 'W',
        customRangeLabel: 'Custom Range',
        daysOfWeek:["日","一","二","三","四","五","六"],
        monthNames: ["一月","二月","三月","四月","五月","六月","七月","八月","九月","十月","十一月","十二月"],
        firstDay:1
      },
      // startDate: moment().subtract(7, "days").format("YYYY-MM-DD HH:mm:ss"),
      startDate: moment().subtract(2,"hours").format("YYYY-MM-DD HH:mm:ss"),
      endDate: moment().format("YYYY-MM-DD HH:mm:ss")
    };
    this.config2 = {
      timePicker:true,
      timePickerIncrement:1,
      singleDatePicker: true,
      timePicker24Hour:true,
      parentEl:$(".wrapper"),
      // maxDate:timeData,
      locale:{
        format:"YYYY-MM-DD HH:00:00",
        separator: " 至 ",
        applyLabel : '确定',
        cancelLabel : '取消',
        fromLabel: '从',
        toLabel: '到',
        weekLabel: 'W',
        customRangeLabel: 'Custom Range',
        daysOfWeek:["日","一","二","三","四","五","六"],
        monthNames: ["一月","二月","三月","四月","五月","六月","七月","八月","九月","十月","十一月","十二月"],
        firstDay:1
      },
      startDate: moment().format("YYYY-MM-DD HH:mm:ss"),
      endDate: moment().format("YYYY-MM-DD HH:mm:ss")
    };

    $("#startTime").daterangepicker(this.config);
    $("#endTime").daterangepicker(this.config2);
  }

//图表数据处理
  /*initButtonEvent(){
    $(".search").click(function(){
      let startTime = $("#startTime").val();
      console.log(startTime);
      let endTime = $("#endTime").val();
	  let monitorCode = $("#monitorCode").val();
      this.echartDataObj = {"startTime":startTime,"endTime":endTime,"monitorCode":monitorCode}
      this.getTraceSourceData(this.echartDataObj);
    }.bind(this));
  }*/

 search(){
     let startTime = $("#startTime").val();
      console.log(startTime);
      let endTime = $("#endTime").val();
	  let monitorCode = $("#monitorCode").val();
      this.echartDataObj = {"startTime":startTime,"endTime":endTime,"monitorCode":monitorCode}
      this.getTraceSourceData(this.echartDataObj);
  }


  //图表数据
  getTraceSourceData(obj){
    this.sourceService.getTraceSourceData(obj).subscribe(
      result => this.responseUtil.success(result,this.getTraceSourceResult),
      message => this.responseUtil.error(message)
    );
  }
  private getTraceSourceResult = (result: MsgResult) =>{
    if (result && result.code == MsgConstants.MSG_CODE_OK) {
      this.getTraceSourceResultResultTree(result.data);
    }
    if (result && result.code != MsgConstants.MSG_CODE_OK) {
      this.dialogService.info(result.message);
    }
  }
  private getTraceSourceResultResultTree(data){
    if(data == [] || data == null){
      //$(".dropdown-menu .list-inline").html("暂无数据");
      $("#traceSourceElementChart").html("<div class='one-message-null'></div>");
      $("#traceSourceSourcesChart").html("<div class='one-message-null'>暂无数据</div>");
      $("#traceSourceResultChart").html("<div class='one-message-null'></div>");
    }else{
      console.log("图表数据加载成功");
      console.log(data)
      this.chartRender(data);
    }
  }

  //获取图标
   getEcharts(divName)
{
  let chart = echarts.getInstanceByDom(document.getElementById(divName));
  if(chart){
    return chart;
  }
  return echarts.init(document.getElementById(divName));
}

   formatterSource (params){
    let strRet = '';
    for(let i=0;i<params.length;i++){
      if(params[i].dataIndex!=-1){
        this.pieCharts.curSel = params[i].dataIndex;
        this.pieCharts.pieName = params[i].name;
        strRet += params[i].name+"</br>";
        break;
      }
    }

    for(let i=0;i<params.length;i++){
      if(params[i].value!=null && params[i].value!=0){
        strRet+="<span style='display:inline-block;margin-right:5px;border-radius:10px;width:9px;height:9px;background-color:"+params[i].color+";'></span>";
        strRet+=params[i].seriesName+" : "+(params[i].value*100.0).toFixed(2)+"%</br>";
      }
    }
    strRet.slice(0,-5);
    return strRet;
  }

  formatterElements(params){
    let strRet = '';
    for(let i=0;i<params.length;i++){
      if(params[i].dataIndex!=-1){
        strRet += params[i].name+"</br>";
        break;
      }
    }
    for(let i=0;i<params.length;i++){
      if(params[i].value!=null && params[i].value!=0 && !isNaN(params[i].value)){
        strRet+="<span style='display:inline-block;margin-right:5px;border-radius:10px;width:9px;height:9px;background-color:"+params[i].color+";'></span>";
        strRet+=params[i].seriesName+" : "+(params[i].value*100.0).toFixed(2)+"%</br>";
      }
    }
    strRet.slice(0,-5);
    return strRet;
  }

  //    图表
  chartRender(chartList){
    this.iniCharts();

    //初始化SourceCharhts
    this.setSource(chartList);
    //初始化污染元素图
    this.setElement(chartList);
    //初始化饼图
    this.setSourceResult(chartList);
  }

  iniCharts(){
    let tsSourcesChart =  this.getEcharts('traceSourceSourcesChart');
    let tsElementChart = this.getEcharts('traceSourceElementChart');
    let tsResultChart = this.getEcharts('traceSourceResultChart');
    //初始化污染源图
    let optionSourcesChart = {
      title: {
        text: 'PM2.5颗粒物',

      },
      tooltip: {
        position: 'inside',
        trigger: 'axis',
        formatter:(params) => this.formatterSource(params)
      },
      legend: {
        data:[]
      },
      xAxis: {
        type: 'category',
        nameGap:'20',
        name: "日期",
        nameLocation:'start',
        boundaryGap: false,
        data: [] ,
      },
      yAxis: {
        name: "指数",
        type: 'value'
      },
      series: []
    };
    tsSourcesChart.setOption(optionSourcesChart);


    let optionElementChart = {
      title: {
        text: '成分含量',
        padding: [
          5,  // 上
          0, // 右
          0,  // 下
          0, // 左
        ]
      },
      tooltip: {
        trigger: 'axis',
        formatter:(params) => this.formatterElements(params)
      },
      legend: {
        data:[]
      },
      xAxis: {
        type: 'category',
        nameGap:"20",
        name: "日期",
        nameLocation:"start",
        boundaryGap: false,
        data: [] ,
      },
      yAxis: {
        name: "指数",
        type: 'value'
      },
      dataZoom: [
        {
          type: 'slider',
          xAxisIndex: 0,
          filterMode: 'empty'
        },
        {
          type: 'inside',
          xAxisIndex: 0,
          filterMode: 'empty'
        }
      ],
      series: []
    };
    tsElementChart.setOption(optionElementChart);

    let optionResult = {
      title:{
        text:'PM2.5溯源结果',
        x: 'center',
        show:true
      },
      tooltip: {
        trigger: 'item',
        //formatter:'{a} <br/>{b}:{d}'
        formatter: function(params){
          let retStr = params.name+' <br/>'+params.seriesName+" : "+(params.value*100).toFixed(2)+"%";
          return retStr;
        }
      },
      legend: {
        orient: 'horizontal',
        bottom: 2
      },
      series: [{
        name:'PM2.5溯源',
        type:'pie',
        selectedMode: 'single',
        radius: [0,80],
        x: 'right',
        label: {
          normal: {
            position: 'outer',
            formatter:'{b}:{d}%'
          }
        },
        labelLine: {
          normal: {
            show: true
          }
        },
        data:[]
      }]
    };
    tsResultChart.setOption(optionResult);


  }

//初始化污染源图
  setSource(chartList){
    let tsSourcesChart =  this.getEcharts('traceSourceSourcesChart');
      if(chartList && chartList.timeList.length>0 && chartList.sourcesDataList.length>0){
        //初始化污染源图
        let optionSourcesChart = {
          title: {
            text: 'PM2.5颗粒物'
          },
          tooltip: {
            position: 'inside',
            trigger: 'axis',
            formatter:(params) => this.formatterSource(params)
          },
          legend: {
            data:chartList.sourcesNameList
          },
          xAxis: {
            type: 'category',
            nameGap:'20',
            name: "日期",
            nameLocation:'start',
            boundaryGap: false,
            data: chartList.timeList ,
          },
          yAxis: {
            name: "指数",
            type: 'value'
          },
          series: []
        };
        //series中的内容
        $.each(chartList.sourcesNameList,function(index,nameList){
          optionSourcesChart.series.push({"type":"line","smooth":true,"name":nameList,"stack":"总量","areaStyle": {normal: {}},"data":chartList.sourcesDataList[index]})
        });
        tsSourcesChart.setOption(optionSourcesChart);
        return;
      }

    let op = tsSourcesChart.getOption();
     op.xAxis.data = [];
     op.series = [];
     tsSourcesChart.dispose();
     tsSourcesChart = echarts.init(document.getElementById("traceSourceSourcesChart"));
     tsSourcesChart.setOption(op);
  }
//初始化污染源成分图
  setElement(chartList){
    let tsElementChart = this.getEcharts('traceSourceElementChart');
    if(chartList&&chartList.timeList.length>0&&chartList.elementsDataList.length>0){
        let optionElementChart = {
          title: {
            text: '成分含量'
          },
          tooltip: {
            trigger: 'axis',
            formatter:(params) => this.formatterElements(params)
          },
          legend: {
            data:chartList.elementNameList
          },
          xAxis: {
            type: 'category',
            nameGap:"20",
            name: "日期",
            nameLocation:"start",
            boundaryGap: false,
            data: chartList.timeList ,
          },
          yAxis: {
            name: "指数",
            type: 'value'
          },
          dataZoom: [
            {
              type: 'slider',
              xAxisIndex: 0,
              filterMode: 'empty'
            },
            {
              type: 'inside',
              xAxisIndex: 0,
              filterMode: 'empty'
            }
          ],
          series: []
        };
        //series中的内容
        $.each(chartList.elementNameList,function(index,nameList){
          optionElementChart.series.push({"type":"line","smooth":true,"name":nameList,"stack":"总量","areaStyle": {normal: {}},"data":chartList.elementsDataList[index]})
        });
        tsElementChart.setOption(optionElementChart);
        return;
      }

    let op = tsElementChart.getOption();
    op.xAxis.data = [];
    op.series = [];
    tsElementChart.dispose();
    tsElementChart = echarts.init(document.getElementById('traceSourceElementChart'));
    tsElementChart.setOption(op);

  }
//初始化污染源结果图
  setSourceResult(chartList){
    let tsResultChart = this.getEcharts('traceSourceResultChart');
      if(chartList && chartList.timeList.length>0 && chartList.sourcesDataList.length>0){
            let optionResult = {
              title:{
                text:'PM2.5溯源结果',
                x: 'center',
                show:true
              },
              tooltip: {
                trigger: 'item',
                //formatter:'{a} <br/>{b}:{d}'
                formatter: function(params){
                  let retStr = params.name+' <br/>'+params.seriesName+" : "+(params.value*100).toFixed(2)+"%";
                  return retStr;
                }
              },
              legend: {
                orient: 'horizontal',
                bottom: 2
              },
              series: [{
                name:'PM2.5溯源',
                type:'pie',
                selectedMode: 'single',
                radius: [0,80],
                x: 'right',
                label: {
                  normal: {
                    position: 'outer',
                    formatter:'{b}:{d}%'
                  }
                },
                labelLine: {
                  normal: {
                    show: true
                  }
                },
                data:[]
              }]
            };
            tsResultChart.setOption(optionResult);
            this.iniPieData(chartList.timeList,chartList.sourcesDataList,chartList.sourcesNameList);
            return;
      }
    let op = tsResultChart.getOption();
   // op.xAxis.data = [];
    op.title.subtext = '';
    op.series = [];
    tsResultChart.dispose();
    tsResultChart = echarts.init(document.getElementById("traceSourceResultChart"));
    tsResultChart.setOption(op);
  }

  changeData(){
    if(this.pieCharts.curSel>=0 && this.pieCharts.curSel<this.pieCharts.pies.length){
      this.SetSrcPieData(this.pieCharts.pieName,this.pieCharts.pies[this.pieCharts.curSel]);
    }
  }


  //初始化饼图数据
  iniPieData(timeList,sourcesDataList,sourcesNameList){
    let pieName = '';
    let pies = [];
    for(var i=0;i<timeList.length;i++){
      if(i==0){
        pieName = timeList[0];
      }
      let pie = [];
      for(var j=0;j<sourcesDataList.length;j++){
        pie.push({
          name:sourcesNameList[j],
          value:sourcesDataList[j][i],
        });
      }
      pies.push(pie);
    }

    this.pieCharts.pieName = pieName;
    this.pieCharts.pies = pies;

    if(pies.length>0){
      this.SetSrcPieData(pieName,pies[0]);
    } else{
      this.SetSrcPieData('','');
    }

  }

   SetSrcPieData(subtitle,raw) {
        if(raw){
          for(let i=0;i<raw.length;){
            // 去掉0或空值
            if(raw[i].value<=0 || raw[i].value==null){
              raw.splice(i,1);
            }else{
              i++;
            }
          }
        }

        let op = {
          title: {
            subtext: subtitle
          },
          series: [{
            data:raw
          }]
        };
        let c = this.getEcharts('traceSourceResultChart');
        c.setOption(op);
      }

}
